package team

import (
	"sanguo/cluster"
	"sanguo/node/common/transaction"
	"sanguo/node/node_team"
	"sanguo/rpc/teamToGameMsg"

	cs_msg "sanguo/protocol/cs/message"
	ss_msg "sanguo/protocol/ss/message"
	ss_rpc "sanguo/protocol/ss/rpc"

	"github.com/golang/protobuf/proto"
	"github.com/sniperHW/kendynet"
)

func onGameToTeam(session kendynet.StreamSession, msg proto.Message) {
	req := msg.(*ss_msg.GameToTeam)

	_team := TeamMgr.GetTeam(req.GetTeamID())
	if _team != nil {
		if req.GetMsgType() == ss_msg.GTTType_KickTeammate {
			_role := _team.GetRole(req.GetRoleID())
			if _role != nil {

				toGame := &ss_rpc.TeamToGameMsgReq{
					MsgType: ss_rpc.TTGType(ss_rpc.TTGType_Kick_Role).Enum(),
					RoleID:  proto.Uint64(_role.RoleID),
					UserID:  proto.String(_role.UserID),
				}
				teamToGameMsg.AsynCall(_role.Game, toGame, transaction.TransTimeoutMs, func(respMsg *ss_rpc.TeamToGameMsgResp, err error) {
					if nil == err && respMsg.GetOk() == 1 {
						_team.KickRole(_role)
						node_team.Infoln("ToGame TTGType_Kick_Role ok")
					} else {
						node_team.Infoln("ToGame TTGType_Kick_Role fail", respMsg, err)
					}
				})

			}
		} else if req.GetMsgType() == ss_msg.GTTType_CallTeammate {

			call := &cs_msg.CallTeammateToC{
				MapID: proto.Int32(req.GetMapID()),
				PosX:  proto.Int32(req.GetPosX()),
				PosY:  proto.Int32(req.GetPosY()),
				PosZ:  proto.Int32(req.GetPosZ()),
			}

			for _, r := range _team.GetRoles() {
				if r.RoleID != _team.Header {
					r.SendToClient(call)
				}
			}
		}

	}

}

func init() {
	cluster.Register(&ss_msg.GameToTeam{}, func(session kendynet.StreamSession, msg proto.Message) {
		onGameToTeam(session, msg)
	})

}
